// Package utildownload contains some internal download functions utilized
// by the primary mobsql app logic.
package utildownload

import (
	"crypto/sha256"
	"fmt"
	"git.sr.ht/~mil/mobsql/logger"
	"git.sr.ht/~mil/mobsql/utilfiles"
	"io"
	"net/http"
	"os"
)

func DownloadURLCached(url, extension string) (string, bool, error) {
	var (
		filenameFriendly = func(input string) string {
			sha := sha256.New()
			sha.Write([]byte(url))
			return fmt.Sprintf("%x", sha.Sum(nil))
		}(url)
		toFilepath = utilfiles.CacheDir("") + filenameFriendly + extension
	)

	if utilfiles.FileExists(toFilepath) {
		return toFilepath, false, nil
	} else {
		return toFilepath, true, DownloadURL(url, toFilepath)
	}
}

func DownloadURL(url, downloadToFilepath string) error {
	logger.Infof("Attempting to download source URL %s to %s", url, downloadToFilepath)
	defer logger.Infof("Downloaded source URL %s to %s ok", url, downloadToFilepath)

	if resp, err := http.Get(url); err != nil {
		return fmt.Errorf("Failed to retrieve gtfs source URL %s: %w", url, err)
	} else if dst, err := os.Create(downloadToFilepath); err != nil {
		return fmt.Errorf("Failed to create desintation filepath %s", downloadToFilepath, err)
	} else if bytes, err := io.ReadAll(resp.Body); err != nil {
		return fmt.Errorf("Failed to write to body: %w", err)
	} else if _, err := dst.Write(bytes); err != nil {
		return fmt.Errorf("Failed to write to target destination file %s: %w", downloadToFilepath, err)
	}
	return nil
}
